const { Paragraph, TextRun, Table, TableCell, TableRow, WidthType, HeightRule, VerticalAlign, BorderStyle, PageBreak, AlignmentType } = require("docx");
const { getAlignment, getIndentValue, getPrefixSymbol } = require("../common/utils");

function generatePasteUnit(field, baseIndent = 0) {
  const { 
    fieldName,
    innerText,
    styleType = 'style1',
    width, 
    height, 
    alignment = 'indent-0',
    prefixSymbol = 'none',
    isBold = false
  } = field.value || {};

  const finalIndent = getIndentValue(alignment, baseIndent);
  const elements = [];
  
  // 1. Display Field Name as a separate paragraph
  if (fieldName && fieldName.trim()) {
    elements.push(new Paragraph({
      indent: { left: finalIndent },
      alignment: getAlignment(alignment),
      spacing: { before: 100, after: 100, line: 360 },
      children: [
        new TextRun({ text: getPrefixSymbol(prefixSymbol), size: 21, font: "SimSun" }),
        new TextRun({ text: ` ${fieldName}`, size: 21, font: "SimSun", bold: isBold })
      ]
    }));
  }

  // 根据样式类型设置默认值
  const defaultInnerText = styleType === 'style2' ? '报告单粘贴页' : '样本编号标签\\n粘贴处';
  const defaultWidth = styleType === 'style2' ? 12 : 5;
  const defaultHeight = 4;
  
  const finalInnerText = innerText || defaultInnerText;
  const finalWidth = width || defaultWidth;
  const finalHeight = height || defaultHeight;

  const widthTwips = cmToTwips(finalWidth);
  const heightTwips = cmToTwips(finalHeight);

  // 处理内部文本
  const innerParagraphs = finalInnerText.split('\\n').map(line => 
    new Paragraph({
      alignment: AlignmentType.CENTER,
      spacing: { before: 50, after: 50, line: 360 },
      children: [
        new TextRun({ text: line, size: 21, font: "SimSun", bold: true }),
      ],
    })
  );

  if (styleType === 'style2') {
    const table = new Table({
        rows: [
            new TableRow({
                children: [
                    new TableCell({
                        children: innerParagraphs,
                        verticalAlign: VerticalAlign.CENTER,
                        width: { size: widthTwips, type: WidthType.DXA },
                        borders: {
                            top: { style: BorderStyle.SINGLE, size: 4, color: "666666" },
                            bottom: { style: BorderStyle.SINGLE, size: 4, color: "666666" },
                            left: { style: BorderStyle.SINGLE, size: 4, color: "666666" },
                            right: { style: BorderStyle.SINGLE, size: 4, color: "666666" },
                        },
                        shading: { fill: "F0F0F0" },
                        margins: { top: 200, bottom: 200, left: 200, right: 200 }
                    }),
                ],
                height: { value: heightTwips, rule: HeightRule.EXACT },
            }),
        ],
        width: { size: widthTwips, type: WidthType.DXA },
        alignment: AlignmentType.CENTER,
    });
    
    const spacingParagraph = new Paragraph({ spacing: { line: 360 }, children: [] });
    elements.push(...Array(15).fill(spacingParagraph));
    elements.push(table);
    elements.push(...Array(12).fill(spacingParagraph));
    // REMOVED: Page break is now handled by the parent renderer
    // elements.push(new Paragraph({ children: [new PageBreak()] }));
  } else {
    // 2. For Style 1, add extra indent to the box
    // Estimate fieldName width in twips (approximate)
    const fieldNameWidth = (fieldName.length + (getPrefixSymbol(prefixSymbol) ? 1 : 0)) * 240; // Approx 240 twips per char
    const tableIndent = finalIndent + fieldNameWidth + 120; // Add a small gap

    const table = new Table({
        rows: [
            new TableRow({
                children: [
                    new TableCell({
                        children: innerParagraphs,
                        verticalAlign: VerticalAlign.CENTER,
                        width: { size: widthTwips, type: WidthType.DXA },
                        borders: {
                            top: { style: BorderStyle.SINGLE, size: 4, color: "333333" },
                            bottom: { style: BorderStyle.SINGLE, size: 4, color: "333333" },
                            left: { style: BorderStyle.SINGLE, size: 4, color: "333333" },
                            right: { style: BorderStyle.SINGLE, size: 4, color: "333333" },
                        },
                        shading: { fill: "FFFFFF" },
                    }),
                ],
                height: { value: heightTwips, rule: HeightRule.EXACT },
            }),
        ],
        width: { size: widthTwips, type: WidthType.DXA },
        indent: { size: tableIndent, type: WidthType.DXA },
    });
    elements.push(table);
  }
    
  return elements;
}

// Helper function to convert cm to twips
function cmToTwips(cm) {
  return cm * 567;
}

module.exports = {
  generatePasteUnit,
};